package com.sunday.common.mq.rabbit.study.base.e6_Header;

import com.rabbitmq.client.*;
import com.sunday.common.mq.rabbit.study.base.ConnectionUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * input key b c
 */
@Slf4j
public class EmitLogHeader {

    private static final String EXCHANGE_NAME = "header_test";

    public static void main(String[] argv) throws Exception {

        Scanner scan = new Scanner(System.in);//实例化Scanner对象
        log.info("请输入文本:");
        argv = scan.nextLine().split(" ");//接受用户输入的字符串

        if (argv.length < 1) {
            System.err.println("Usage: EmitLogHeader message queueName [headers]...");
            System.exit(1);
        }

        // API需要一个路由密钥，但实际上如果你使用报头交换
        //路由键值不用于路由。你可以存储信息
        //接收方的路由密钥在接收到的消息中仍然可用。
        String routingKey = "ourTestRoutingKey";

        String message = argv[0];

        Map<String, Object> headers = new HashMap<String, Object>();

        //剩下的参数是键值头对。为了这个目的
        //例如，我们假设它们都是字符串，但RabbitMQ不需要这样做
        for (int i = 1; i < argv.length; i++) {
            log.info("Adding header {} with value {} to Map {}", argv[i], argv[i + 1]);
            headers.put(argv[i], argv[i + 1]);
            i++;
        }

        ConnectionFactory factory = ConnectionUtil.factory();

        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {

            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.HEADERS);

            AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();

            // MessageProperties。PERSISTENT_TEXT_PLAIN是AMQP的静态实例。BasicProperties
            //包含一个交付模式和一个优先级。所以我们把它们传递给建造者。
            builder.deliveryMode(MessageProperties.PERSISTENT_TEXT_PLAIN.getDeliveryMode());
            builder.priority(MessageProperties.PERSISTENT_TEXT_PLAIN.getPriority());

            builder.headers(headers);

            AMQP.BasicProperties theProps = builder.build();

            // 现在我们添加标题。本例只使用字符串头，但它们也可以是整数
            channel.basicPublish(EXCHANGE_NAME, routingKey, theProps, message.getBytes("UTF-8"));
            log.info("[x] Sent message: '{}'", message);
        }
    }
}

